package com.demo.steammanagement.utils;

import com.demo.steammanagement.model.entity.Users;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Spring Security用户详情类
 * 实现UserDetails接口，用于封装用户信息和权限
 */
public class SecurityUser implements UserDetails {

    /**
     * 封装的用户实体对象
     */
    private final Users users;

    public SecurityUser(Users users) {
        this.users = users;
    }

    /**
     * 获取用户权限信息
     * 根据用户角色返回对应的权限列表
     *
     * @return 用户的权限集合
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 根据用户角色设置权限
        if ("1".equals(users.getUserRole())) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        String password = users.getPassword();
        users.setPassword(null);
        return password;
    }

    @Override
    public String getUsername() {
        return users.getAccount();
    }

    /**
     * 判断账号是否未过期
     * 管理员账号永不过期
     *
     * @return true 如果账号未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        if ("1".equals(users.getUserRole())) {
            return true;
        }
        LocalDateTime expirationDate = users.getAccountExpirationDate();
        if (expirationDate == null) {
            return false;
        }
        return expirationDate.isAfter(LocalDateTime.now());
    }

    /**
     * 判断账号是否未锁定
     *
     * @return true 如果账号未被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        // 状态为1表示正常，0表示冻结
        return users.getStatus() == 1;
    }

    /**
     * 判断凭证是否未过期
     *
     * @return true 凭证未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        // 默认凭证不过期
        return true;
    }

    /**
     * 判断账号是否可用
     *
     * @return true 如果账号可用
     */
    @Override
    public boolean isEnabled() {
        return isAccountNonLocked() && isAccountNonExpired();
    }

    /**
     * 获取原始用户对象
     *
     * @return Users实体对象
     */
    public Users getUsers() {
        return users;
    }
}
